package com.insigma.business.qrcode.soldier.service.impl;

import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.business.qrcode.soldier.util.ThreadPoolManager;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component
public class TrafficComponent {

    private static Logger logger = LoggerFactory.getLogger(TrafficComponent.class);

    @Autowired
    private RedisUtils redisUtils;


    public void incTrafficCount(String api) {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String format = DateFormatUtils.format(new Date(), "MM-dd");
                    String key = "traffic_" + format + "_" + api;
                    redisUtils.increment(key, 1L);
                    redisUtils.expire(key, TimeUnit.DAYS.toSeconds(14L));
                } catch (Exception e) {
                    logger.error("流量统计时，错误：{}", e);
                }
            }
        });
    }

    public Integer getApiCount(String api) {
        String format = DateFormatUtils.format(new Date(), "MM-dd");
        String key = "traffic_" + format + "_" + api;
        Object o = redisUtils.get(key);
        if (o != null) {
            return (Integer)o;
        }
        return null;
    }

}

